package org.example.utils;


import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//3. 记录每秒分贝大小
public class voice {

//    public static void main(String[] args) {
//        String inputFilePath = "D:\\heima-java\\ssm\\01-spring\\day02\\代码\\spring\\demo23232\\hm-dianping\\upload\\voice\\2024\\12\\06/12月6日 下午5点54分.wav"; // 替换为实际文件路径
//
//        try {
//            analyzeAudioVolumeVoice(inputFilePath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    // 分析音频的音量并输出每秒的分贝值
    public  String analyzeAudioVolumeVoice(String inputFilePath) throws UnsupportedAudioFileException, IOException {
        File audioFile = new File(inputFilePath);
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
        AudioFormat format = audioInputStream.getFormat();
        byte[] audioBytes = audioInputStream.readAllBytes();
        int bytesPerFrame = format.getFrameSize();
        int numFrames = audioBytes.length / bytesPerFrame;

        int sampleRate = (int) format.getSampleRate();
        int framesPerSecond = sampleRate;  // 每秒的帧数

        Map<Integer, List<Float>> secondVolumes = new HashMap<>(); // 每秒的音量数据

        for (int i = 0; i < numFrames; i++) {
            int sampleIndex = i * bytesPerFrame;
            float frameVolume = 0;

            if (bytesPerFrame == 2) {
                short sample = (short) ((audioBytes[sampleIndex + 1] << 8) | (audioBytes[sampleIndex] & 0xFF));
                frameVolume = Math.abs(sample) / 32768.0f;
            } else if (bytesPerFrame == 4) {
                short sampleLeft = (short) ((audioBytes[sampleIndex + 1] << 8) | (audioBytes[sampleIndex] & 0xFF));
                short sampleRight = (short) ((audioBytes[sampleIndex + 3] << 8) | (audioBytes[sampleIndex + 2] & 0xFF));
                frameVolume = (Math.abs(sampleLeft) + Math.abs(sampleRight)) / (2 * 32768.0f);
            }

            // 获取当前帧所在的秒数
            int second = i / framesPerSecond;

            // 将每秒的音量数据记录下来
            secondVolumes.computeIfAbsent(second, k -> new ArrayList<>()).add(frameVolume);
        }
        String num="";
        // 输出每秒的分贝值
        for (Map.Entry<Integer, List<Float>> entry : secondVolumes.entrySet()) {
            int second = entry.getKey();
            List<Float> volumes = entry.getValue();

            // 计算该秒内的平均音量
            double avgVolume = volumes.stream().mapToDouble(v -> v).average().orElse(0.0);
            // 转换为分贝
            float dB = 20 * (float) Math.log10(avgVolume);
            if(num=="") {
                num+=dB;
            } else {
                num+=" "+dB;
            }
            System.out.printf("第 %d 秒的平均音量: %.2f dB\n", second, dB);
        }

        return num;             //把每秒的平均分贝叠加起来成功String      用到的时候spilt切割
    }
}
